package com.dragon.mmochat.model.scheduleJob.pkGame.activities;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.message.Mmochat_1_1S;
import com.dragon.mmochat.model.MmochatChenHao;
import com.dragon.mmochat.model.MmochatTeam;
import com.dragon.mmochat.model.battle.MmochatBattle;
import com.dragon.mmochat.model.enumType.MmochatBattleType;
import com.dragon.mmochat.model.enumType.MmochatChenHaoType;
import com.dragon.mmochat.model.enumType.MmochatEquipAttributeType;
import com.dragon.mmochat.model.enumType.MmochatEventType;
import com.dragon.mmochat.model.enumType.MmochatNpcFaceType;
import com.dragon.mmochat.model.enumType.MmochatNpcItemType;
import com.dragon.mmochat.model.enumType.MmochatPropType;
import com.dragon.mmochat.model.enumType.MmochatRoleBmpType;
import com.dragon.mmochat.model.enumType.MmochatRoleStateType;
import com.dragon.mmochat.model.enumType.MmochatTeamConditionType;
import com.dragon.mmochat.model.enumType.MmochatTeamStateType;
import com.dragon.mmochat.model.map.MmochatMap;
import com.dragon.mmochat.model.map.MmochatMapTransPoint;
import com.dragon.mmochat.model.object.MmochatEquip;
import com.dragon.mmochat.model.object.MmochatEquipAttribute;
import com.dragon.mmochat.model.object.MmochatProp;
import com.dragon.mmochat.model.role.MmochatNpc;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.service.MmochatBattleService;
import com.dragon.mmochat.service.MmochatChatService;
import com.dragon.mmochat.service.MmochatDao;
import com.dragon.mmochat.service.MmochatEquipService;
import com.dragon.mmochat.service.MmochatFeedService;
import com.dragon.mmochat.service.MmochatMainService;
import com.dragon.mmochat.service.MmochatMapService;
import com.dragon.mmochat.service.MmochatNpcService;
import com.dragon.mmochat.service.MmochatTeamService;
import com.dragon.mmochat.util.MmochatUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

//个人争霸赛
public class MmochatPersonalPkGame implements MmochatPkGame {

	private static final int minPlayer = 2; // 开赛最少人数要求
	private static final int initScore = 4; // 个人争霸赛初始积分

	private static Logger log = LoggerFactory
			.getLogger(MmochatWuDaoPkGame.class);
	private static ScheduledExecutorService pkThreadPool = Executors
			.newScheduledThreadPool(10);
	private static List<ScheduledFuture<?>> scheduleHandleList = new ArrayList<ScheduledFuture<?>>();
	public static Map<Integer, Boolean> wuDaoPkGameOverMap = new ConcurrentHashMap<Integer, Boolean>();
	public static Map<Integer, Boolean> wuDaoPkGameAwardMap = new ConcurrentHashMap<Integer, Boolean>();

	@Override
	public void prepare() {
		try {
			int index = 0;
			for (int mapId = MmochatConstant.mapId_30级个人赛; mapId < MmochatConstant.mapId_MAX等级个人赛; mapId++) {
				try {
					MmochatMap map = new MmochatMap();
					map.setMapId(mapId);
					// TODO:地图文件待定
					map.setMapDataId(MmochatConstant.mapDataId_个人赛);
					map.setCanChangeLine(false);
					map.setWalkToBattle(false);
					map.setCanFriendlyPk(false);
					map.setCanTransToFriend(false);
					map.setCanWatchPk(false);
					map.setTeamCondition(MmochatTeamConditionType.不允许组队);
					map.setMapName("个人争霸场");

					// 增加地图传送NPC
					MmochatNpc npc = new MmochatNpc();
					npc.setNpcId(MmochatConstant.npcId_wuDaoPkNpc1Base + index);
					npc.setMapId(mapId);
					npc.setX((short) 286);
					npc.setY((short) 284);
					npc.setName("赛场传送人");
					npc.setBmpType(MmochatRoleBmpType.老头儿);
					npc.setFace(MmochatNpcFaceType.朝左);
					npc.getFunctionItems().add(MmochatNpcItemType.退出会场前往余杭);
					npc.getFunctionItems().add(MmochatNpcItemType.退出会场前往江宁);
					npc.getFunctionItems().add(MmochatNpcItemType.退出会场前往开封);
					map.addNpc(npc);
					MmochatNpcService.npcs.put(npc.getNpcId(), npc);

					MmochatMapService.maps.put(map.getMapId(), map);
					index++;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			MmochatChatService.sendSystemMsg("个人争霸赛即将开始,请大家到江宁找"
					+ MmochatUtil.wrapColor("云中子(30,708)", Color.yellow)
					+ "进入场地!比赛将于20:00开始!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 每人3个积分, 系统随机匹配两队战斗,败者输1分,胜者平分败方所输积分.
	// 只剩一队时获取. 时间结束时存在多个队伍则积分最高的获胜.
	@Override
	public void start() {
		try {
			scheduleHandleList.clear();
			wuDaoPkGameOverMap.clear();
			wuDaoPkGameAwardMap.clear();
			for (int mapId = MmochatConstant.mapId_30级个人赛; mapId < MmochatConstant.mapId_MAX等级个人赛; mapId++) {
				try {
					MmochatMap map = MmochatMapService.maps.get(mapId);
					if (map == null) {
						continue;
					}
					wuDaoPkGameOverMap.put(mapId, false);
					Map<Integer, MmochatPlayer> updateMap = new ConcurrentHashMap<Integer, MmochatPlayer>();
					for (int line = 0; line < MmochatConstant.maxMapLineNum; line++) {
						if (map.getLineRoleMap(line).size() < minPlayer) {
							// 人数不足,比赛结束
							for (MmochatPlayer me : map.getLineRoleMap(line)
									.values()) {
								kickOutFromWuDaoPkGame(me);
								updateMap.put(me.getRoleId(), me);
								MmochatChatService.sendSystemMsgToPerson(me,
										"您所在级别段的个人争霸赛因参与人数不足" + minPlayer
												+ "人,无法开赛!");
								log.debug(me.getName() + "因人数不足离开个人争霸赛.");
							}
						} else {
							// 人数足够,设置每个玩家初始积分
							for (MmochatPlayer me : map.getLineRoleMap(line)
									.values()) {
								me.setCommonActivityScore(initScore);
								MmochatChatService.sendSystemMsgToPerson(me,
										"比赛即将开始，您的个人争霸赛初始积分为" + initScore
												+ "分。积分不足1分将无法继续比赛。");
							}

							// 开始比赛,每隔2分钟自动匹配队伍对战,直到只剩最后一名或一队
							ScheduledFuture<?> fightHandle = pkThreadPool
									.scheduleWithFixedDelay(
											new RandomTeamFight(map, line), 10,
											60, TimeUnit.SECONDS);
							scheduleHandleList.add(fightHandle);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void end() {
		try {
			// 停止战斗线程
			closeFightThread();
			Map<Integer, MmochatPlayer> updateMap = new ConcurrentHashMap<Integer, MmochatPlayer>();
			for (int mapId = MmochatConstant.mapId_30级个人赛; mapId < MmochatConstant.mapId_MAX等级个人赛; mapId++) {
				try {
					MmochatMap map = MmochatMapService.maps.get(mapId);
					if (map == null) {
						continue;
					}

					// 改变状态
					if (wuDaoPkGameOverMap.get(map.getMapId()) != null
							&& !wuDaoPkGameOverMap.get(map.getMapId())) {
						synchronized (map) {
							if (!wuDaoPkGameOverMap.get(map.getMapId())) {
								wuDaoPkGameOverMap.put(map.getMapId(), true);
							} else {
								continue;
							}
						}
						// 发放奖励,剩下的玩家按积分最高的队伍获胜
						dealAward(map);
					}

					// 将地图内的所有人转移到固定地图,并解散队伍
					for (int line = 0; line < MmochatConstant.maxMapLineNum; line++) {
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							kickOutFromWuDaoPkGame(me);
							updateMap.put(me.getRoleId(), me);
						}
					}
					MmochatMapService.maps.remove(map.getMapId());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			MmochatChatService.sendSystemMsg("本次个人争霸赛已圆满结束!");
			// try {
			// MmochatDao.batchUpdateRoleLeavePkGame(updateMap.values());
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 停止自动匹配战斗
	public static void closeFightThread() {
		try {
			for (ScheduledFuture<?> handle : scheduleHandleList) {
				try {
					handle.cancel(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			scheduleHandleList.clear();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 自动随机匹配战斗
	// 空闲的玩家未经系统操作不会变成战斗状态
	// 战斗状态的玩家可能在匹配过程中变成空闲状态
	class RandomTeamFight implements Runnable {
		private MmochatMap map;
		private int line;

		public RandomTeamFight(MmochatMap map, int line) {
			this.map = map;
			this.line = line;
		}

		@Override
		public void run() {
			try {
				// 检测比赛是否结束
				if (isWuDaoPkOver(map, line)) {
					return;
				}

				List<MmochatPlayer> freePlayerList = new ArrayList<MmochatPlayer>();
				// 掉线或离开地图的玩家会自动从地图玩家中去除
				Map<Integer, MmochatPlayer> updateMap = new ConcurrentHashMap<Integer, MmochatPlayer>();
				for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
					if (!me.isInBattle() && me.getCommonActivityScore() <= 0) {
						// 积分不足，请出武道会
						kickOutFromWuDaoPkGame(me);
						updateMap.put(me.getRoleId(), me);
						MmochatChatService.sendSystemMsgToPerson(me,
								"您的个人争霸赛积分不足，被请离了会场。");
					}

					// 空闲的个人或队长
					if (me.getCommonActivityScore() > 0
							&& !me.isInBattle()
							&& MmochatTeamService.getTeamState(me) != MmochatTeamStateType.队员) {
						// 锁定状态,锁定后不能组队,不能加人,不能离图
						if (me.lockState(MmochatRoleStateType.准备进入武道会战斗)) { // ?何时unlock,不要漏了
							freePlayerList.add(me);
						}
					}
				}
				if (freePlayerList.size() > 1) {
					// 乱序排序
					Collections.shuffle(freePlayerList);

					int fightTeamNum = freePlayerList.size() / 2;

					// 可能其中一方在此时掉线或离开游戏,但仍将以自动战斗方式参加战斗
					// 如果战斗结束时发现此人不在此地图或离线,则判断其为弃权
					for (int i = 0; i < fightTeamNum; i++) {
						// 第一队人
						MmochatPlayer person1 = freePlayerList.get(2 * i);
						List<MmochatPlayer> team1 = new ArrayList<MmochatPlayer>();
						if (person1.isInTeam()) {
							MmochatTeam team = MmochatTeamService.teams
									.get(person1.getTeamId());
							if (team == null) {
								person1.leaveTeam();
								team1.add(person1);
							} else {
								for (Integer roleId : team.getMemberId()
										.values()) {
									MmochatPlayer member = MmochatMainService.players
											.get(roleId);
									if (member != null) {
										team1.add(member);
									}
								}
							}
						} else {
							team1.add(person1);
						}

						// 第二队人
						MmochatPlayer person2 = freePlayerList.get(2 * i + 1);
						List<MmochatPlayer> team2 = new ArrayList<MmochatPlayer>();
						if (person2.isInTeam()) {
							MmochatTeam team = MmochatTeamService.teams
									.get(person2.getTeamId());
							if (team == null) {
								person2.leaveTeam();
								team2.add(person2);
							} else {
								for (Integer roleId : team.getMemberId()
										.values()) {
									MmochatPlayer member = MmochatMainService.players
											.get(roleId);
									if (member != null) {
										team2.add(member);
									}
								}
							}
						} else {
							team2.add(person2);
						}

						if (team1.contains(person2) || team2.contains(person1)) {
							// 同一队...应该不可能出现
							person1.unLockState();
							person2.unLockState();
							continue;
						}
						// 进入战斗
						person1.unLockState();
						person2.unLockState();
						MmochatBattle battle = MmochatBattleService
								.enterPVPBattle(map.getMapId(), (byte) line,
										team1, team2, MmochatBattleType.个人争霸赛);

						// 不允许逃跑
						if (battle != null) {
							battle.setCanEscape(false);
							try {
								Thread.sleep(50);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
				for (MmochatPlayer me : freePlayerList) {
					if (me.getState() == MmochatRoleStateType.准备进入武道会战斗) {
						me.unLockState();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	// 武道会是否结束
	public static boolean isWuDaoPkOver(MmochatPlayer me) {
		if (me == null) {
			return true;
		}
		// TODO:与MmochatNpcService中的level_line_map要一致
		// level->line, 30,40,50,60,70,80,90,100,110,120
		int[] level_line_map = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		int teamIndex = me.getLevel() / 10 - 3;
		if (teamIndex < 0 || teamIndex >= level_line_map.length) {
			return true;
		}

		// 进入比武场
		int targetMapId = MmochatConstant.mapId_30级个人赛 + teamIndex;
		MmochatMap map = MmochatMapService.getMapByMapId(targetMapId);
		if (map == null) {
			return true;
		}
		return isWuDaoPkOver(map, me.getLine());
	}

	// 将玩家请离武道会
	public static void kickOutFromWuDaoPkGame(MmochatPlayer me) {
		MmochatMapTransPoint newPos = MmochatMap.getMapWhenTempMapNotFound(me
				.getMapId());
		MmochatMap map1 = MmochatMapService.getMapByMapId(newPos
				.getTransToMapId());

		// 停止战斗
		if (me.isInBattle()) {
			MmochatBattle battle = MmochatBattleService.battles.get(me
					.getBattleId());
			if (battle != null) {
				battle.closeBattle();
			}
		}

		// 积分清0
		me.setCommonActivityScore(0);

		// 离开队伍
		if (me.isInTeam()) {
			MmochatTeam team = MmochatTeamService.teams.get(me.getTeamId());
			team.leaveTeam(me.getRoleId());
		}

		// TODO:其它处理
		if (!me.lockState(MmochatRoleStateType.切换地图时)) {
			log.debug("玩家" + me.getName() + "(skyid=" + me.getSkyId()
					+ ")当前状态为<" + me.getState().toString() + ">,无法传送");
			return;
		}

		// 停止交易
		me.stopDeal();

		// 清除周围玩家
		me.getSceenRoles().clear();

		// 清除坐标缓存器
		me.getPositionBuffer().clear();

		// 清除NPC列表
		me.getTmpNpcs().clear();

		// 从旧地图中删除玩家
		MmochatMap map = MmochatMapService.maps.get(me.getMapId());
		map.delRole(me.getLine(), me);

		// 设置新坐标
		me.setX(newPos.getNewMapX());
		me.setY(newPos.getNewMapY());
		me.setMapId(newPos.getTransToMapId());

		me.unLockState();

		Mmochat_1_1S pack = new Mmochat_1_1S();
		// 不使用hallState进行判断,以免终端连续上传两次请求后,终端hallState被第二次请求发送时更改
		pack.setMap(map1);
		pack.setLine((int) me.getLine());
		pack.setMe(me);
		MmochatMainService.enterGame(me, me.getUserConnInfo(), pack);
		synchronized (me) {
			// 坐标可能被其它线程修改，用同步保护
			me.setX(newPos.getNewMapX());
			me.setY(newPos.getNewMapY());
			MmochatUtil.sendCommonPack(me, pack);
		}
		log.debug("玩家" + me.getName() + "被送出个人场");

	}

	// 武道会是否结束
	public static boolean isWuDaoPkOver(MmochatMap map, int line) {
		if (map == null || map.getLineRoleMap(line).size() == 0
				|| wuDaoPkGameOverMap.get(map.getMapId()) == null
				|| wuDaoPkGameOverMap.get(map.getMapId())) {
			return true;
		}
		// 检测是否只剩一人或一队
		int teamId = -1;
		for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
			if (me.getCommonActivityScore() > 0) {
				if (teamId == -1) {
					// 第一个被检测的人
					teamId = me.getTeamId();
				} else if (teamId == 0) {
					// 上一个检测的玩家没有队伍
					// 存在两个以上玩家,且其中一个为没队伍.比赛继续
					return false;
				} else if (teamId > 0) {
					// 上一个检测的玩家有队伍
					if (me.getTeamId() != teamId) {
						// 存在两个队伍或一个队伍及一个个人.比赛继续
						return false;
					} else {
						// 队伍ID相同,属同一个队伍,继续检测
						continue;
					}
				}
			}
		}

		// 改变状态
		if (wuDaoPkGameOverMap.get(map.getMapId()) != null
				&& !wuDaoPkGameOverMap.get(map.getMapId())) {
			synchronized (map) {
				if (!wuDaoPkGameOverMap.get(map.getMapId())) {
					wuDaoPkGameOverMap.put(map.getMapId(), true);
				} else {
					return true;
				}
			}
			// 发放奖励
			dealAward(map);

			// 将所有人清出场地
			Map<Integer, MmochatPlayer> updateMap = new ConcurrentHashMap<Integer, MmochatPlayer>();
			for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
				kickOutFromWuDaoPkGame(me);
				updateMap.put(me.getRoleId(), me);
			}
			// try {
			// MmochatDao.batchUpdateRoleLeavePkGame(updateMap.values());
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
		}

		return true;
	}

	// TODO:发放奖励,剩下的玩家按积分最高的队伍获胜
	private static void dealAward(MmochatMap map) {
		if (map == null) {
			return;
		}
		synchronized (map) {
			if (wuDaoPkGameAwardMap.get(map.getMapId()) == null) {
				wuDaoPkGameAwardMap.put(map.getMapId(), true);
			} else {
				return;
			}
		}

		List<MmochatPlayer> teamLeaders = new ArrayList<MmochatPlayer>();
		for (int line = 0; line < MmochatConstant.maxMapLineNum; line++) {
			for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
				if (MmochatTeamService.getTeamState(me) != MmochatTeamStateType.队员) {
					teamLeaders.add(me);
				}
			}
		}
		if (teamLeaders.size() == 0) {
			return;
		}
		Collections.sort(teamLeaders, new MmochatPlayer.sortByCommonScore());
		MmochatPlayer winTeamLeader = teamLeaders.get(0);
		List<MmochatPlayer> members = new ArrayList<MmochatPlayer>();
		if (winTeamLeader.isInTeam()) {
			MmochatTeam team = MmochatTeamService.teams.get(winTeamLeader
					.getTeamId());
			if (team == null) {
				winTeamLeader.leaveTeam();
				members.add(winTeamLeader);
			} else {
				for (Integer roleId : team.getMemberId().values()) {
					MmochatPlayer me = MmochatMainService
							.getRoleFromBuffer(roleId);
					if (me != null) {
						members.add(me);
					}
				}
			}
		} else {
			members.add(winTeamLeader);
		}

		// 第一名玩家获得 300元宝以下的道具随机5个,风神护体3天,橙装1件
		MmochatPropType[] propList = null;
		propList = new MmochatPropType[] { MmochatPropType.锦囊,
				MmochatPropType.喇叭, MmochatPropType.成长丹, MmochatPropType.超级成长丹,
				MmochatPropType.轮回水, MmochatPropType.防冻剂, MmochatPropType.镇定剂,
				MmochatPropType.虚无水, MmochatPropType.迟滞水, MmochatPropType.八卦令,
				MmochatPropType.银联卡, MmochatPropType.赎罪牌, MmochatPropType.后悔药,
				MmochatPropType.混沌石, MmochatPropType.急急如律令,
				MmochatPropType.天尊令, MmochatPropType.道尊令, MmochatPropType.驱兽令,
				MmochatPropType.驭兽令, MmochatPropType.龙涎香, MmochatPropType.小血池,
				MmochatPropType.小法池, MmochatPropType.中法池, MmochatPropType.大法池,
				MmochatPropType.小血玲珑, MmochatPropType.小法玲珑,
				MmochatPropType.中法玲珑, MmochatPropType.大法玲珑 };

		String memberNames = "";
		List<Integer> idList = new ArrayList<Integer>();
		List<String> nameList = new ArrayList<String>();
		int levelRange = (map.getMapId() - MmochatConstant.mapId_30级个人赛) * 10 + 30;

		for (MmochatPlayer me : members) {
			if (me != null) {
				idList.add(me.getRoleId());
				nameList.add(me.getName());

				memberNames += me.getName() + ",";
				String awardMsg = me.getName() + "获得了";
				// 5件随机道具, 10%机率获得一个会员月卡
				if (MmochatUtil.isInPercent(10)) {
					MmochatProp prop = new MmochatProp(MmochatPropType.会员月卡);
					boolean success = me.addObjectToPackage(prop);
					if (!success) {
						MmochatChatService.sendSystemMsgToPerson(me,
								"您的道具包裹已满，无法获得道具奖励。");
					} else {
						awardMsg += "会员月卡,";
					}
				} else {
					for (int i = 0; i < 5; i++) {
						int index = MmochatUtil.getRandomValue(propList.length);
						MmochatPropType type = propList[index];
						MmochatProp prop = new MmochatProp(type);
						boolean success = me.addObjectToPackage(prop);
						if (!success) {
							MmochatChatService.sendSystemMsgToPerson(me,
									"您的道具包裹已满，无法获得道具奖励。");
						} else {
							awardMsg += type.toString() + ",";
						}
					}
				}
				// 风神光环1个
				{
					MmochatPropType type = MmochatPropType.风神护体;
					MmochatProp prop = new MmochatProp(type);
					boolean success = me.addObjectToPackage(prop);
					if (!success) {
						MmochatChatService.sendSystemMsgToPerson(me,
								"您的道具包裹已满，无法获得风神护体。");
					} else {
						awardMsg += type.toString() + ",";
					}
				}
				// 橙装1件
				{
					MmochatEquip equip = MmochatEquipService.getRandEquip(me
							.getLevel(), me.getLevel() + 10, 0, 0, 100);
					boolean success = me.addObjectToPackage(equip);
					if (!success) {
						MmochatChatService.sendSystemMsgToPerson(me,
								"您的装备包裹已满，无法获得装备奖励。");
					} else {
						awardMsg += MmochatUtil.wrapColor(equip.getName(),
								equip.getQuality().getColor())
								+ "的奖励。";
					}
				}
				// 称号奖励
				{
					MmochatChenHao chenhao = new MmochatChenHao();
					chenhao.setType(MmochatChenHaoType.出类拔萃);
					MmochatEquipAttribute attr = new MmochatEquipAttribute();
					attr.setType(MmochatEquipAttributeType.忽视全异常抵抗);
					attr.setValue(8);
					chenhao.addAttr(attr);
					chenhao.setLifeTime(MmochatConstant.MS_PER_DAY * 3);
					chenhao.setExtraEffectInfo("同级别段个人最强王者证明，总时效3天。");
					MmochatChenHao.addAndUpdateChenHaoAndSaveSql(
							me.getRoleId(), chenhao);
				}
				MmochatChatService.sendSystemMsg(awardMsg);
				MmochatFeedService.addFeed(me.getSkyId(),
						"{fromSkyid}在${appName}$本次" + levelRange
								+ "级别段的个人争霸赛中力战群雄，脱颖而出，成为本周的单打王者。");
			}
		}
		String msg = "本次" + levelRange + "级别段的个人争霸赛圆满结束,最终获胜者是";
		msg += MmochatUtil.wrapColor(memberNames, Color.green);
		msg += "特此祝贺!";
		MmochatChatService.sendSystemMsg(msg);

		// 保存日志
		MmochatEventType eventType;
		switch (levelRange) {
		case 30:
			eventType = MmochatEventType.个人赛30级组;
			break;
		case 40:
			eventType = MmochatEventType.个人赛40级组;
			break;
		case 50:
			eventType = MmochatEventType.个人赛50级组;
			break;
		case 60:
			eventType = MmochatEventType.个人赛60级组;
			break;
		case 70:
			eventType = MmochatEventType.个人赛70级组;
			break;
		case 80:
			eventType = MmochatEventType.个人赛80级组;
			break;
		case 90:
			eventType = MmochatEventType.个人赛90级组;
			break;
		case 100:
			eventType = MmochatEventType.个人赛100级组;
			break;
		case 110:
			eventType = MmochatEventType.个人赛110级组;
			break;
		case 120:
			eventType = MmochatEventType.个人赛120级组;
			break;
		default:
			eventType = MmochatEventType.个人赛120级组;
			break;
		}

		Gson gson = new Gson();
		String title = gson.toJson(idList, new TypeToken<List<Integer>>() {
		}.getType());
		String content = gson.toJson(nameList, new TypeToken<List<String>>() {
		}.getType());
		try {
			MmochatDao.addEventLog(eventType.getValue(), System
					.currentTimeMillis(), title, content);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		try {
			MmochatDao.batchUpdateMyPackage(members);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 重新加载
		MmochatNpcService.reloadEventLog();
	}
}
